package com.zzyl.framework.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @作者:zgh
 * @日期:2024/11/11 23:36
 * @描述:小程序端请求拦截器
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.先获取请求头中的token
        String token = request.getHeader("authorization");
        //2.判断token是否为空,如果为空则直接响应401
        if (StrUtil.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("登陆失败");
        }
        //3.token不为空,解析token
        Claims claims = tokenService.parseToken(token);
        //4.判断token是否过期,如果解析失败也响应401
        if(ObjectUtil.isEmpty(claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("登陆失败");
        }
        //5.从token中取出用户id,如果没去到返回401
        Long userId = Long.valueOf(String.valueOf(claims.get("userId")));
        if(ObjectUtil.isEmpty(userId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException("登陆失败");
        }
        //6.如果取到了,把userId放入ThreadLocal中
        UserThreadLocal.set(userId);
        //7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从threadLocal中移除用户id
        UserThreadLocal.remove();
    }
}
